import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/view/examination/question/question_text_widget.dart';
import 'package:kxy_flutter_app/view/examination/widget/blank_widget.dart';
import 'package:kxy_flutter_app/view/examination/widget/option_type.dart';
import '../../../model/exam_question.dart';

class FillBlankQuestionWidget extends StatefulWidget {
  final Question question;
  final Function(List<String>) onChange;
  final bool withResult;

  const FillBlankQuestionWidget({
    Key key,
    @required this.question,
    @required this.onChange,
    this.withResult = false,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _FillBlankQuestionWidgetState();
  }
}

class _FillBlankQuestionWidgetState extends State<FillBlankQuestionWidget> {
  Question question;
  List<String> userAnswerList;
  List<List<String>> rightAnswerList;
  List<int> blankList;
  Function(List<String>) onChange;

  @override
  void initState() {
    super.initState();
    question = widget.question;
    onChange = widget.onChange;
    blankList = new List<int>();
    userAnswerList = new List<String>();
    rightAnswerList = new List<List<String>>();

    if (question.rightAnswer.isNotEmpty) {
      var json = jsonDecode(question.rightAnswer);
      (json as List).forEach((items) {
        rightAnswerList.add((items as List).map((e) => e.toString()).toList());
      });
    }

    for (int i = 0; i < question.blankCount; i++) {
      blankList.add(i);
      userAnswerList.add('');
    }

    if (question.userAnswer.isNotEmpty) {
      int i = 0;
      (jsonDecode(question.userAnswer) as List).forEach((item) {
        userAnswerList[i] = item;
        i++;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
      children: [
        QuestionTextWidget(text: question.title),
        optionListWidget(context),
        if (widget.withResult && question.confirmed) resultWidget(),
      ],
    );
  }

  Widget resultWidget() {
    var question = widget.question;
    var rightAnswer = jsonDecode(question.rightAnswer);
    dynamic userAnswer;
    if (question.userAnswer.isNotEmpty) {
      userAnswer = jsonDecode(question.userAnswer);
    } else {
      userAnswer = [];
    }

    return Container(
      margin: EdgeInsets.only(top: 20),
      padding: EdgeInsets.all(10),
      decoration: BoxDecoration(
        color: Color.fromRGBO(250, 250, 250, 1),
        border: Border.all(color: Color.fromRGBO(230, 230, 230, 1), width: 1),
        borderRadius: BorderRadius.circular(5),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            '答案解析',
            style: TextStyle(fontSize: 16, color: Colors.black54),
          ),
          Padding(
            padding: EdgeInsets.only(top: 10),
            child: Text(
              '正确答案：${(rightAnswer as List).join(',')}',
              style: TextStyle(fontSize: 16),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 10),
            child: Text(
              '您的答案：${(userAnswer as List).join(',')}',
              style: TextStyle(fontSize: 16),
            ),
          ),
          if (question.analysis != null && question.analysis.isNotEmpty)
            Padding(
              padding: EdgeInsets.only(top: 10),
              child: Text(
                '答案解析：${question.analysis}',
                style: TextStyle(fontSize: 16),
              ),
            ),
        ],
      ),
    );
  }

  Widget optionListWidget(BuildContext context) {
    return Container(
      child: Column(
        children: ListTile.divideTiles(
          tiles: blankList.map((i) {
            var option = AnswerOption(
              key: (i + 1).toString(),
              option: userAnswerList[i],
            );
            return BlankWidget(
              option: option,
              type: getType(option, i),
              canModified: !question.confirmed,
              onChange: (str) {
                userAnswerList[i] = str;
                this.onChange(userAnswerList);
              },
            );
          }).toList(),
          context: context,
          color: Color.fromRGBO(240, 240, 240, 1),
        ).toList(),
      ),
    );
  }

  OptionType getType(AnswerOption opt, int indexx) {
    if (!question.confirmed) {
      return OptionType.noraml;
    }

    if (question.answDisorder == true) {
      for (var i = 0; i < userAnswerList.length; i++) {
        if (i == indexx) {
          break;
        }

        var userAnswer = userAnswerList[i];
        var rightIndex = rightAnswerList.indexWhere((item) => item.contains(userAnswer));
        if (rightIndex > -1) {
          rightAnswerList.removeAt(rightIndex);
        }
      }

      var index = rightAnswerList.indexWhere((item) => item.contains(opt.option));
      return index == -1 ? OptionType.error : OptionType.successAndChecked;
    } else {
      var rightAnswerItems = rightAnswerList[indexx];
      if (rightAnswerItems.contains(opt.option)) {
        return OptionType.successAndChecked;
      } else {
        return OptionType.error;
      }
    }
  }
}
